/*
 * @Copyright: Copyright (C) AMCAX, All rights reserved.
 * @Author: 殷建峰
 * @Date: 2025-02-05 19:14:57
 * @LastEditTime: 2025-02-25 15:45:46
 * @LastEditors: 殷建峰
 * @Description:
 */
import { Button, Checkbox, Dropdown, Menu } from 'antd';
import styles from './styles.module.scss';
import { useEffect, useState } from 'react';
import useStateRef from 'react-usestateref';
import { TCmdGroup } from '@/components/types';

interface IProps {
  cmdGroups: TCmdGroup[];
  onChange?: (values: string[]) => void;
}

export default function CmdGroupCheckButton({ cmdGroups, onChange }: IProps) {
  const [visible, setVisible] = useState(false);
  const [selectedValues, setSelectedValues, selectedValuesRef] = useStateRef(
    [],
  );

  useEffect(() => {
    setSelectedValues(
      cmdGroups.filter((item) => item.visible).map((item) => item.id),
    );
  }, [cmdGroups]);

  const handleCheck = (value: string, checked: boolean) => {
    if (checked) {
      setSelectedValues([...selectedValues, value]);
    } else {
      setSelectedValues(selectedValues.filter((v) => v !== value));
    }
    onChange?.(selectedValuesRef.current);
  };

  const handleMenuClick = (e) => {
    console.log('click item', e.key);
  };

  const menu = (
    <Menu
      className={styles.groupCheckBox}
      onClick={handleMenuClick}>
      {cmdGroups.map((item) => (
        <Menu.Item key={item.id}>
          <Checkbox
            checked={selectedValues.includes(item.id)}
            onChange={(e) => handleCheck(item.id, e.target.checked)}>
            {item.label}
          </Checkbox>
        </Menu.Item>
      ))}
    </Menu>
  );

  return (
    <div className={styles.groupCheck}>
      <Dropdown
        popupRender={() => menu}
        trigger={['click']}
        onOpenChange={setVisible}
        open={visible}>
        <Button className={styles.groupCheckButton}>...</Button>
      </Dropdown>
    </div>
  );
}
